/*************************************************************************
	> File Name: shmServer.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/12 14:09
 ************************************************************************/

#include "comm.hpp"

Init init;

std::string TransToHex(key_t k)
{
    char buffer[BUFFER_SIZE];
    snprintf(buffer, sizeof buffer, "0x%x", k);
    return buffer;
}

int main(int argc, char *argv[])
{
    key_t k = ftok(PATH_NAME, PROJ_ID);
    assert(k != -1);
    Log("Create key success", Debug) << " sever key:" << TransToHex(k) << std::endl;
    int shmid = shmget(k, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
    if (shmid  == -1) {
        perror("shmget");
        exit(1);
    }
    Log("Create shm success", Debug) << " shmid:" << shmid << std::endl;
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    Log("Attach shm success", Debug) << " shmid:" << shmid << std::endl;
    int fd = OpenFIFO(FIFO_NAME, READ);
    while (1) {
        Wait(fd);
        printf("%s\n", shmaddr);
        if (strcmp(shmaddr, "quit") == 0) {
            break;
        }
    }
    int n = shmdt(shmaddr);
    assert(n != -1);
    (void)n;
    Log("Detach shm success", Debug) << " shmid:" << shmid << std::endl;
    n = shmctl(shmid, IPC_RMID, nullptr);
    assert(n != -1);
    (void)n;
    Log("Delete shm success", Debug) << " shmid:" << shmid << std::endl;
    return 0;
}



